﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using ExameRegister.Model;
using System.Windows.Data;
using System.IO;
using System.Linq;
using System.Windows.Media.Imaging;

namespace ExameRegister
{
	public partial class PersonnelInfoWindow : ChildWindow
	{
        private ServiceUtility su = new ServiceUtility();
        private string _username = null;
        private string _idcard = null;
        private int _positionid = 0;
        private int errorCount = 0;
        public PersonnelInfoWindow(int positionid, string name, string idcard, int registerStatus)
		{
			// 为初始化变量所必需
			InitializeComponent();
            this.BindingValidationError += (sender, e) =>
            {
                if (e.Action == ValidationErrorEventAction.Added)
                {
                    errorCount++;
                }
                else if (e.Action == ValidationErrorEventAction.Removed)
                {
                    errorCount--;
                }
            };
            closeButton.IsEnabled = false;
            //dtbNative.ParentControl = this;
            _username = name;
            _idcard = idcard;
            _positionid = positionid;
            su.OnCompletedCallService += new EventHandler<WCFEvent>(su_OnCompletedCallService);
            //su.CallService("ExameRegister.BO.LoginBO", "GetPublicOfficialSelection", new object[] { "p.ID=" + positionid }, this, "position");
            su.CallService("ExameRegister.BO.LoginBO", "GetEmp_BasicInfoRegister", new object[] { _username, _idcard, 0 }, this, "Emp_BasicInfoRegister");
            if (registerStatus == 2 || registerStatus == 1)
            {
                SetUIEnableFals();
                commit.IsEnabled = false;
                //zancun.IsEnabled = false;
            }
            
		}
        private System.Collections.Generic.List<byte> pic = new System.Collections.Generic.List<byte>();
        void su_OnCompletedCallService(object sender, WCFEvent e)
        {
            string tag = e.UserState as string;
            if (string.IsNullOrEmpty(tag))
                return; //TextBox
            switch (tag)
            {
                case "position":
                    SetPosition(e.Result);
                    su.CallService("ExameRegister.BO.LoginBO", "GetEmp_BasicInfoRegister", new object[] { _username, _idcard, _positionid }, this, "Emp_BasicInfoRegister");
                    break;
                case "Emp_BasicInfoRegister":
                    if (!string.IsNullOrEmpty(e.Result))
                    {
                        var en = Utility.ConvertFromJson<Emp_BasicInfoRegister>(e.Result);
                        en.IsValidate = true;
                        this.DataContext = en;
                        if (en.ID > 0)//已有简历
                        {
                            this.Title = "";
                            closeButton.IsEnabled = true;
                        }
                        ResetField();
                        if (en.HasPhoto == true)
                        {
                            UploadFileInfo file = new UploadFileInfo() { IsFinished = false, key = "photo", Name = en.PhotoName, start = 0, Size = 1600 };
                            su.CallService("ExameRegister.BO.LoginBO", "DownLoadFile", new object[] { file }, this, "DownLoadFile");
                        }
                    }
                    else
                    {
                        Emp_BasicInfoRegister ebr = new Emp_BasicInfoRegister() { PositionID = _positionid };
                        this.DataContext = ebr;
                        ResetField();
                    }
                    break;
                case "DownLoadFile":
                    UploadFileInfo Downfile = Utility.ConvertFromJson<UploadFileInfo>(e.Result);
                    if (Downfile == null || Downfile.Context == null)
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("简历照片不存在!");
                        break;
                    }

                    pic.AddRange(Downfile.Context);
                    //foreach (byte b in Downfile.Context)
                    //{
                    //    pic.Add(b);
                    //}
                    if (Downfile.IsFinished == true)
                    {
                        using (MemoryStream ms = new MemoryStream(pic.ToArray<byte>()))
                        {
                            BitmapImage b = new BitmapImage();

                            //mm.Write(_item.icon, 0, _item.icon.Length);
                            b.SetSource(ms);
                            img.Source = b;
                        }
                    }
                    else
                    {
                        Downfile.start += Downfile.Size;
                        Downfile.Context = null;
                        su.CallService("ExameRegister.BO.LoginBO", "DownLoadFile", new object[] { Downfile }, this, "DownLoadFile");
                    }
                    break;
                case "Register":
                    bool result = Utility.ConvertFromJson<bool>(e.Result);
                    if (result)
                    {
                        SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功");
                        this.DialogResult = true;
                    }
                    else
                    {
                        SilverlightMessageBoxLibrary.Message.InfoMessage("保存失败：已报名，简历不能更改");
                        closeButton.IsEnabled = true;
                    }
                    break;
            }
        }

        void ResetField()
        {
            //dtbFullDegree.Field = dtbFullDegree.Field;
            //dtbFullEducationBg.Field = dtbFullEducationBg.Field;
            //dtbGender.Field = dtbGender.Field;
            //dtbHealth.Field = dtbHealth.Field;
            //dtbNative.Field = dtbNative.Field;
            //dtbPartDegree.Field = dtbPartDegree.Field;
            //dtbPartEducationBg.Field = dtbPartEducationBg.Field;
            //dtbPolitical.Field = dtbPolitical.Field;
        }

        void SetPosition(string result)
        {
            //ObservableCollection<PublicOfficialSelection> position = Utility.ConvertFromJson<ObservableCollection<PublicOfficialSelection>>(result);
            //if (position.Count == 1)
            //{
            //    tbDW.Text = position[0].XXDW;
            //    tbDepartMent.Text = position[0].Department;
            //    tbPosition.Text = position[0].Duty;
            //   // (root.Resources["IsEnableClass"] as PIWBinding).Status = position[0].Status; 
               
               
            //}
        }

        void SetUIEnableFals()
        {
            ///tb
            tbCJAP.IsEnabled = false;
            tbDSC.IsEnabled = false;
            //tbDutyL.IsEnabled = false;
            tbFSAM.IsEnabled = false;
            tbHomeaddress.IsEnabled = false;
            tbJC.IsEnabled = false;
            //tbKHR.IsEnabled = false;
            //tbKHR2.IsEnabled = false;
            //tbKHR3.IsEnabled = false;
            //tbNP.IsEnabled = false;
            tbPhone.IsEnabled = false;
            tbPSAM.IsEnabled = false;
            tbT.IsEnabled = false;
            tbWE.IsEnabled = false;
            dpBirthPlace.IsEnabled = false;
            //dpKET2.IsEnabled = false;
            //dpKHt.IsEnabled = false;
           // dpKHT3.IsEnabled = false;
             dpWorkDate.IsEnabled = false;
            datePicker2.IsEnabled = false;
            datePicker3.IsEnabled = false;
            datePicker4.IsEnabled = false;
            //dtbFullDegree.IsEnabled = false;
            //dtbFullEducationBg.IsEnabled = false;
            //dtbGender.IsEnabled = false;
            //dtbHealth.IsEnabled = false;
            //dtbNative.IsEnabled = false;
            //dtbPartDegree.IsEnabled = false;
            //dtbPartEducationBg.IsEnabled = false;
            //dtbPolitical.IsEnabled = false;
            
                
        }

       
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            GetValue();
            if (!UpdateSource())
                return;
           
            if (position != null && entity != null)
            {
                position.Status = 0;
                su.CallService("ExameRegister.BO.LoginBO", "Register", new object[] { position, entity, Sessions.Session[Sessions.EXAMENATION] }, this, "Register");
            }
        }

        /// <summary>
        /// 验证
        /// </summary>
        /// <returns></returns>
        bool UpdateSource()
        {
            BindingExpression beUsername = tbPhone.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();
            beUsername = tbHomeaddress.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();
            beUsername = LXDH.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();
            beUsername = tbCJAP.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();
            beUsername = tbFSAM.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();
            beUsername = tbPSAM.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();
            beUsername = tbWE.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();
            beUsername = tbJC.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();
            beUsername = tbT.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();
            beUsername = tbemail.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();

            beUsername = dpBirthPlace.GetBindingExpression(DatePicker.SelectedDateProperty);
            beUsername.UpdateSource();
            beUsername = dpWorkDate.GetBindingExpression(DatePicker.SelectedDateProperty);
            beUsername.UpdateSource();
            beUsername = datePicker2.GetBindingExpression(DatePicker.SelectedDateProperty);
            beUsername.UpdateSource();
            beUsername = datePicker3.GetBindingExpression(DatePicker.SelectedDateProperty);
            beUsername.UpdateSource();
            beUsername = datePicker4.GetBindingExpression(DatePicker.SelectedDateProperty);
            beUsername.UpdateSource();
     

            if (errorCount > 0)
            {
                return false;
            }
            if (string.IsNullOrEmpty(entity.DutyLevel))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("现任职务层次不能为空!");
                return false;
            }
            if(string.IsNullOrEmpty(entity.Gender)){
                SilverlightMessageBoxLibrary.Message.ErrorMessage("性别不能为空!");
                return false;
            }
            if (string.IsNullOrEmpty(entity.NativePlace))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("籍贯不能为空!");
                return false;
            }
            if (string.IsNullOrEmpty(entity.Native))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("民族为空!");
                return false;
            }
            if (string.IsNullOrEmpty(entity.Political))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("政治面貌为空!");
                return false;
            }
            if (string.IsNullOrEmpty(entity.Health))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("健康状况为空!");
                return false;
            }
            if (string.IsNullOrEmpty(entity.FullEducationBg) && string.IsNullOrEmpty(entity.PartEducationBg))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("全日制和在职学历必须填一个");
                return false;
            }
            if (string.IsNullOrEmpty(entity.FullEducationBg) && string.IsNullOrEmpty(entity.DutyAttribute))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("职位属性必填");
                return false;
            }
            if (string.IsNullOrEmpty(entity.KaoHeResult1))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("考核结果为空!");
                return false;
            }
            if (string.IsNullOrEmpty(entity.KaoHeResult2))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("考核结果为空!");
                return false;
            }
            if (string.IsNullOrEmpty(entity.KaoHeResult3))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("考核结果为空!");
                return false;
            }
            return true;
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            //GetValue();
            ////BindingExpression beUsername = tbTitle.GetBindingExpression(TextBox.TextProperty);
            ////beUsername.UpdateSource();
            ////int count = Validation.GetErrors().Count;
            //if (errorCount > 0)//判断是否有验证失败
            //    return;
            //if (position != null && entity != null)
            //{
            //    position.Status = 3;
            //    su.CallService("ExameRegister.BO.LoginBO", "Register", new object[] { position, entity, Sessions.Session[Sessions.EXAMENATION] }, this, "Register");
            //}
        }

        private Emp_BasicInfoRegister entity = null;
        private RegisterPosition position = null;
        void GetValue()
        {
            entity = this.DataContext as Emp_BasicInfoRegister;
            position = new RegisterPosition() { PositionID = _positionid, EmpID = entity.EmpID, Name = entity.Name, CardNo = entity.CardNo };

        }
	}

    public class PIWBinding
    {
        public int Status = 0;
    }
}